fork download
  1. //Enter you code here.
  2. //Please indent properly.
  3.  
  4. <?php
  5. //program to find the common elements of the two array
  6. //here we have to array A and B from which w have to find the common element
  7. //first we sort then using merge sort and after then for traversing through
  8. //the array in one iteration we can find the comman elements the given array
  9. //this is an inspace algorithm meansno extra space is needed
  10.  
  11. //best case time complexity=O(nlogn)
  12. //O(nlogn)-> for sorting
  13. //O(n)-> for while loop to find comman element
  14.  
  15. //average case time complexity=O(nlogn)
  16. //O(nlogn)-> for sorting
  17. //O(n)-> for while loop to find comman element
  18.  
  19. //worst case time complexity =O(nlogn)
  20. //O(nlogn)-> for sorting
  21. //O(n)-> for while loop to find comman element
  22.  
  23.  
  24.  
  25. $commonArray=array();
  26. $A=array(3,4,5,6,7,8,9,10,36,58,27,48);
  27. $B=array(3,10,4,5,6,8,12,24,37,27,50);
  28. sort($A);
  29. sort($B);
  30. $size1=sizeof($A);
  31. $size2=sizeof($B);
  32. $counter1=0;
  33. $counter2=0;
  34. while(($counter1< $size1) && ($counter2)<($size2))//traversing through the array
  35. {
  36.  
  37. if ($A[$counter1] == $B[$counter2])
  38. {
  39. array_push($commonArray,$A[$counter1]); //to enter comman element in the output array
  40. $counter1=$counter1+1;
  41. $counter2=$counter2+1;
  42. }
  43. else if ($A[$counter1] < $B[$counter2])
  44. {
  45. $counter1=$counter1+1; }
  46.  
  47. else
  48. {
  49. $counter2=$counter2+1;
  50. }
  51. }
  52.  
  53. print_r($commonArray);//to print the output array
  54. ?>
  55.  
  56.  
Success #stdin #stdout 0.02s 25940KB
stdin
Standard input is empty
stdout
//Enter you code here.
//Please indent properly.

Array
(
    [0] => 3
    [1] => 4
    [2] => 5
    [3] => 6
    [4] => 8
    [5] => 10
    [6] => 27
)